util.AddNetworkString( "OpenPresetSelect" )

ENT.Type = "point"

ENT.Arena_YellowDoor = nil
ENT.Arena_GreenDoor = nil
ENT.Arena_Music = nil

RPGDM_GreenContestants = {}
RPGDM_YellowContestants = {}

ENT.SortedPlayers = {}

ENT.PlayerCount = 0

RPGDM_NextMap = "rpgdm_lobby_01g_pak1"
RPGDM_WaitForNum = 2
RPGDM_WaitingForPlayers = false
RPGDM_WaitingForPlayersMax = 15
RPGDM_RoundStartTime = 30
RPGDM_RoundLength = 90
RPGDM_MaxPlayersPerRound = 6
RPGDM_CurRound = 1
RPGDM_MaxRounds = 5
RPGDM_InRound = false
RPGDM_StartedCountdown = false
RPGDM_DeterminingWinner = false

function ENT:Initialize()
	RPGDM_GameType = "arena"
	self.Arena_YellowDoor = ents.FindByName("YELLOWDOOR")
	self.Arena_GreenDoor = ents.FindByName("GREENDOOR")
	self.Arena_Music = ents.FindByName("ARENAMUSIC")
	
	file.Write("rpgdm/currentgametype.txt", "arena/n")
end

function ENT:ChooseContestants()
	local numoneach = RPGDM_MaxPlayersPerRound;
	print("Choosing contestants.")
	for k = 1, numoneach do
		if(self.SortedPlayers[k] == nil and !IsValid(self.SortedPlayers[k]) or !self.SortedPlayers[k]:IsPlayer())then
			print("bork")
			return true
		end
		if(#team.GetPlayers(1) < #team.GetPlayers(2))then
			self.SortedPlayers[k]:SetTeam(1)
			table.insert(RPGDM_GreenContestants, self.SortedPlayers[k])
		elseif(#team.GetPlayers(1) > #team.GetPlayers(2))then
			self.SortedPlayers[k]:SetTeam(2)
			table.insert(RPGDM_YellowContestants, self.SortedPlayers[k])
		else
			local rand = math.random(1, 2)
			if(rand == 1)then
				self.SortedPlayers[k]:SetTeam(1)
				table.insert(RPGDM_GreenContestants, self.SortedPlayers[k])
			else
				self.SortedPlayers[k]:SetTeam(2)
				table.insert(RPGDM_YellowContestants, self.SortedPlayers[k])
			end
		end
		GivePlayerSelectedPreset(self.SortedPlayers[k])
		self.SortedPlayers[k]:Spawn()
		self.SortedPlayers[k].Contestant = true
		MatchData.PlayerProgress[self.SortedPlayers[k]:SteamID()] = {{0, ClassData.BaseXP, 8}, {0, 0, 0, 0, 0, 0}}
		net.Start("SendPlayerProgress")
		net.WriteTable(MatchData.PlayerProgress[self.SortedPlayers[k]:SteamID()][2])
		net.Send(self.SortedPlayers[k])
		ApplyTalents(self.SortedPlayers[k])
	end
end

function ENT:AddRoundsSatOut()

end

function ENT:SortPlayers()
	self.SortedPlayers = player.GetAll()
	local i = 1
	while(i<(self.PlayerCount)) do
		local v = self.SortedPlayers[i] 
		if(v.RoundsWaited == nil or self.SortedPlayers[i+1].RoundsWaited == nil)then	
			if(v.RoundsWaited == nil)then
				v.RoundsWaited = 0
			end
			if(self.SortedPlayers[i+1].RoundsWaited == nil)then
				self.SortedPlayers[i+1].RoundsWaited = 0
			end
		end
		if(v.RoundsWaited < self.SortedPlayers[i+1].RoundsWaited)then
			local tempvalue = nil
			tempvalue = v
			self.SortedPlayers[i] = self.SortedPlayers[i+1]
			self.SortedPlayers[i+1] = tempvalue
			i = 1
		end
		i = i + 1
	end
end

function ENT:DetermineWinner()
	RPGDM_StartedCountdown = true
	local tempwinner = ""
	RPGDM_CurRound = RPGDM_CurRound + 1
	RPGDM_WaitingForPlayers = true
	
	if((#RPGDM_GreenContestants && #RPGDM_YellowContestants == 0) || #RPGDM_GreenContestants > #RPGDM_YellowContestants)then
		for k, v in pairs(RPGDM_GreenContestants)do
			local options = util.JSONToTable(file.Read("rpgdm/playerdata/"..v:SteamID64().."/options.txt", "DATA"))
			if(options.ArenaWins and options.ArenaWins > 0)then
				options.ArenaWins = options.ArenaWins + 1
			else
				options.ArenaWins = 1
			end
			print(options.ArenaWins)
			UpdatePlayerOptions(v, util.TableToJSON(options))
		end
		tempwinner = "Green"
		net.Start("GreenVictory")
		net.Broadcast()
	else
		for k, v in pairs(RPGDM_YellowContestants)do
			local options = util.JSONToTable(file.Read("rpgdm/playerdata/"..v:SteamID64().."/options.txt", "DATA"))
			if(options.ArenaWins and options.ArenaWins > 0)then
				options.ArenaWins = options.ArenaWins + 1
			else
				options.ArenaWins = 1
			end
			print(options.ArenaWins)
			UpdatePlayerOptions(v, util.TableToJSON(options))
		end
		tempwinner = "Yellow"
		net.Start("YellowVictory")
		net.Broadcast()
	end
	RPGDM_GreenContestants = {}
	RPGDM_YellowContestants = {}
	if(self.Arena_GreenDoor != nil)then
		for k, v in pairs(self.Arena_GreenDoor)do
			v:Fire("Close")
		end
	end
	if(self.Arena_YellowDoor != nil)then
		for k, v in pairs(self.Arena_YellowDoor)do
			v:Fire("Close")
		end
	end
	CreateVisualTimer(5,  
			function()
				RPGDM_InRound = false
				RPGDM_GameOver = false
				RPGDM_StartedCountdown = false
				RPGDM_DeterminingWinner = false
			end, 
			""..tempwinner.." wins!",
			"devin/blackbetty/hudicons/ctf.png")
end


function ENT:StartRound()
	RPGDM_InRound = true
	print("Starting round #"..RPGDM_CurRound.."")
	if(self.Arena_GreenDoor != nil)then
		for k, v in pairs(self.Arena_GreenDoor)do
			v:Fire("Open")
		end
	end
	if(self.Arena_YellowDoor != nil)then
		for k, v in pairs(self.Arena_YellowDoor)do
			v:Fire("Open")
		end
	end
	if(self.Arena_Music != nil)then
		for k, v in pairs(self.Arena_Music)do
			v:Fire("StartSound")
		end
	end
end

function ENT:StartPlayerWait()
	print("Starting wait sequence.")
	
	CreateVisualTimer(RPGDM_WaitingForPlayersMax,  
		function()
			game.ConsoleCommand("changelevel".." ".."rpgdm_lobby_01g_pak1\n")
		end, 
		"Waiting for players...",
		"devin/blackbetty/hudicons/arena.png")
end

function ENT:Think()
	print(""..#RPGDM_GreenContestants..":"..#RPGDM_YellowContestants.."")
	self.PlayerCount = table.Count(player.GetAll())
	if(self.PlayerCount > 0)then
		self:SortPlayers()
		if(!RPGDM_WaitingForPlayers and self.PlayerCount < RPGDM_WaitForNum and !RPGDM_InRound)then
			self:StartPlayerWait()
			RPGDM_WaitingForPlayers = true
		end
		if(RPGDM_WaitingForPlayers and self.PlayerCount >= RPGDM_WaitForNum and !RPGDM_InRound)then
			RPGDM_WaitingForPlayers = false
			self:ChooseContestants()
			timer.Destroy("Waiting for players...")
			CreateVisualTimer(RPGDM_RoundStartTime,  
				function()
					self:StartRound()
					RPGDM_StartedCountdown = false
				end, 
				"Starting round.",
				"devin/blackbetty/hudicons/arena.png")
		end
		if(RPGDM_InRound and !RPGDM_StartedCountdown)then
			RPGDM_StartedCountdown = true
			CreateVisualTimer(RPGDM_RoundLength,  
				function()
					RPGDM_StartedCountdown = false
				end, 
				"Fight!",
				"devin/blackbetty/hudicons/dm.png")
		end
		if(RPGDM_InRound and RPGDM_StartedCountdown and !RPGDM_GameOver and !RPGDM_DeterminingWinner)then
			if(#RPGDM_YellowContestants == 0 or #RPGDM_GreenContestants == 0)then
				timer.Destroy("Fight!")
				RPGDM_DeterminingWinner = true
				CreateVisualTimer(3,  
				function()
					self:DetermineWinner()
				end, 
				"Determining winner...",
				"devin/blackbetty/hudicons/plus.png")
			end
		end
		self:NextThink( CurTime() + 0.2 )
	end
end

hook.Add("ShowHelp", "ChoosePresetOnF1", function(ply)
	net.Start("OpenPresetSelect")
	net.Send(ply)
end)

hook.Add("PlayerSpawn", "FlagOnSpawn", function(ply) 
	if(ply.Flag != nil)then
		ply.Flag:Remove()
		ply.Flag = nil
	end
	GiveFlagTo(ply, ply:Team()) 
end) 

hook.Add("PlayerDeath", "FlagOnSpawn", function(ply) 
	if(ply.Flag != nil)then
		ply.Flag:Remove()
		ply.Flag = nil
	end
	if(RPGDM_GameType == "arena")then
		StripPlayer(ply)
	end
	if(ply:Team() == TEAM_YELLOW)then
		ply.tempSpells = ClassData.DefaultSpells[player_manager.GetPlayerClass(ply)]
		for k, v in pairs(RPGDM_YellowContestants)do
			if(v:EntIndex() == ply:EntIndex())then
				local options = util.JSONToTable(file.Read("rpgdm/playerdata/"..v:SteamID64().."/options.txt", "DATA"))
				if(options.ArenaLosses and options.ArenaLosses > 0)then
					options.ArenaLosses = options.ArenaLosses + 1
				else
					options.ArenaLosses = 1
				end
				UpdatePlayerOptions(v, util.TableToJSON(options))
				table.remove(RPGDM_YellowContestants, k)
				break
			end
		end
	elseif(ply:Team() == TEAM_GREEN)then
		ply.tempSpells = ClassData.DefaultSpells[player_manager.GetPlayerClass(ply)]
		for k, v in pairs(RPGDM_GreenContestants)do
			if(v:EntIndex() == ply:EntIndex())then
				local options = util.JSONToTable(file.Read("rpgdm/playerdata/"..v:SteamID64().."/options.txt", "DATA"))
				if(options.ArenaLosses and options.ArenaLosses > 0)then
					options.ArenaLosses = options.ArenaLosses + 1
				else
					options.ArenaLosses = 1
				end
				UpdatePlayerOptions(v, util.TableToJSON(options))
				table.remove(RPGDM_GreenContestants, k)
				break
			end
		end
	end
	ply:SetTeam(3)
end)

